/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cs575.coresystem;

import cs575.dbentities.Session;
import cs575.dbentities.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import javax.persistence.EntityManager;

/**
 *
 * @author bms
 */
public class NewAuthentication {

    private EntityManager em;

    public NewAuthentication() {
        this.em = null;
    }

    public NewAuthentication(EntityManager em) {
        this.em = em;
    }

    public Session authenticate(Session userSession) {
        Session ret = null;
        try {
            if (validate(userSession)) {
                Date expireTime = null;
                Session dbSession = (Session) em.createNamedQuery("Session.findBySessionKey").setParameter("sessionKey", userSession.getSessionKey()).getSingleResult();
                if (dbSession != null) {
                    expireTime = dbSession.getExpireTime();
                    // Check the expiration time
                    if (expireTime.after(new Date())) {
                        ret = dbSession;
                    }
                }
            }
        } catch (Exception e) {
        }

        return ret;
    }

    public Session authenticate(String username, String password) {
        Session userSession = null;
        try {
            User user = (User) em.createNamedQuery("User.findByUserName").setParameter("userName", username).getSingleResult();
            if (user != null) {
                if (user.getPassword().equals(password)) {
                    userSession = createSessionEntry(user.getUserId());
                }
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
        return userSession;
    }

    public Boolean endSession(Session session) {
        return deleteSessionEntry(session.getSessionKey());
    }

    private boolean validate(Session userSession) {
        if (userSession != null) {
            return true;
        } else {
            return false;
        }
    }

    private String generateSessionKey(int user_id) {
        return UUID.randomUUID().toString().replaceAll("[-]", "");
    }

    private Session createSessionEntry(int user_id) {
        Session userSession = null;
        try {
            // generate a new session key
            String tmpSession = generateSessionKey(user_id);
            // create a timestamp for the a week
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, 7);
            Date time = c.getTime();
            em.getTransaction().begin();
            Session previousSession = em.find(Session.class, user_id);
            if (previousSession != null) {
                userSession = new Session(user_id, previousSession.getSessionKey(), time);
                em.merge(userSession);
            } else {
                userSession = new Session(user_id, tmpSession, time);
                em.persist(userSession);
            }
            em.getTransaction().commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return userSession;
    }

    private Boolean deleteSessionEntry(String session_key) {
        Boolean res = false;
        Connection conn = null;
        try {
            Session dbSession = (Session) em.createNamedQuery("Session.findBySessionKey").setParameter("sessionKey", session_key).getSingleResult();
            if (dbSession != null) {
                em.getTransaction().begin();
                em.remove(dbSession);
                em.getTransaction().commit();
            }
            res = true;
        } catch (Exception e) {
        } finally {
        }
        return res;
    }
}
